<template>
  <view class="container">
    <u-navbar
      :is-fixed="true"
      :border-bottom="false"
      :is-back="true"
      :background="{ background: '#fff' }"
      :title="title"
      title-color="#000"
    >
    </u-navbar>
    <u-toast ref="uToast" />
    <view class="content">
      <u-form :model="form" ref="uForm" :label-width="150">
        <u-form-item label="姓名"
          ><u-input v-model="form.realname" placeholder="请输入真实姓名"
        /></u-form-item>
        <u-form-item label="手机号" prop="phone"
          ><u-input v-model="form.phone" placeholder="请输入手机号"
        /></u-form-item>
        <u-form-item label="证件类型">
          <u-input
            v-model="form.cardtype"
            placeholder="请选择"
            type="select"
            @click="showType = true"
          />
          <u-action-sheet
            :list="typeList"
            v-model="showType"
            @click="chooseType"
          ></u-action-sheet>
        </u-form-item>
        <u-form-item label="证件号码"
          ><u-input v-model="form.cardno" placeholder="请输入证件号码"
        /></u-form-item>
        <u-form-item label="旅客类型">
          <u-input
            v-model="form.pType"
            placeholder="请选择"
            type="select"
            @click="showType2 = true"
          />
          <u-action-sheet
            :list="typeList2"
            v-model="showType2"
            @click="chooseType2"
          ></u-action-sheet>
        </u-form-item>
      </u-form>
    </view>
    <view class="imgs" v-if="form.id && form.pics.length">
      <image
        class="img"
        v-for="(img, index) in form.pics"
        :key="index"
        :src="img"
      ></image>
      <button class="submit submit2" @click="reSubmit(form.examine)">
        {{ form.examine === "true" ? "已认证" : "重新上传" }}
      </button>
    </view>
    <u-upload
      v-if="form.pType !== '成人' && form.pType !== '儿童' && !previewImg"
      :maxCount="3"
      ref="uUpload"
      :action="action"
      :file-list="fileList"
    ></u-upload>
    <button class="submit" @click="doAdd">{{ btnName }}</button>
  </view>
</template>

<script>
import { addPass, updatePass, updateUser } from "../../api/system/api";
import moment from "moment";
export default {
  data() {
    return {
      action: "http://127.0.0.1:3000/upload",
      fileList: [],
      form: {
        realname: "",
        phone: "",
        cardtype: "",
        cardno: "",
        pType: "",
      },
      title: "添加乘车人",
      rules: {
        phone: [
          {
            max: 11,
            message: "手机号不能超过11位",
            trigger: "change",
          },
        ],
      },
      showType: false,
      showType2: false,
      btnName: "添加",
      typeList: [
        {
          text: "中国居民身份证",
        },
        {
          text: "港澳台居民来往内地通行证",
        },
        {
          text: "台湾居民来往大陆通行证",
        },
        {
          text: "护照",
        },
      ],
      typeList2: [
        {
          text: "成人",
        },
        {
          text: "儿童",
        },
        {
          text: "学生",
        },
        {
          text: "残军",
        },
      ],
      userInfo: {},
      previewImg: false,
    };
  },
  onLoad(option) {
    // 该页面为添加\编辑乘车人页面  如果有别的页面携带的参数 说明是修改
    if (option.data) {
      this.form = JSON.parse(option.data);
      if (this.form.id) {
        this.btnName = "修改";
        this.title = "编辑乘车人";
        // 展示证件类型\旅客类型的中文
        this.form.cardtype = this.typeList[Number(this.form.cardtype)].text;
        this.form.pType = this.typeList2[Number(this.form.pType)].text;
        this.form.pics = JSON.parse(this.form.pics);
        // 处理图片 拼接地址
        this.form.pics.forEach((v, i) => {
          this.form.pics[i] = `http://127.0.0.1:3000/${v}`;
        });
        this.previewImg = true;
      }
    }
  },
  onReady() {
    // form表单的规则校验
    this.$refs.uForm.setRules(this.rules);
  },
  created() {
    // 获取当前用户信息的缓存
    uni.getStorage({
      key: "userInfo",
      success: (res) => {
        this.userInfo = res.data;
      },
    });
  },
  methods: {
    // 选择证件类型
    chooseType(index) {
      this.form.cardtype = this.typeList[index].text;
    },
    // 选择旅客类型
    chooseType2(index) {
      this.form.pType = this.typeList2[index].text;
      if (this.form.pType === "学生" || this.form.pType === "残军") {
        // 开启图片上传功能
        this.previewImg = false;
      } else {
        this.previewImg = true;
        // 清空图片
        this.form.pics = [];
      }
    },
    // 添加乘客
    doAdd() {
      // 对于表单项的校验
      if (!this.form.realname) {
        this.$refs.uToast.show({
          title: "请输入姓名",
          type: "error",
        });
        return;
      }
      if (!this.form.phone) {
        this.$refs.uToast.show({
          title: "请输入手机号",
          type: "error",
        });
        return;
      }
      if (!this.form.cardtype) {
        this.$refs.uToast.show({
          title: "请选择证件类型",
          type: "error",
        });
        return;
      }
      if (!this.form.cardno) {
        this.$refs.uToast.show({
          title: "请输入证件号",
          type: "error",
        });
        return;
      }
      if (!this.form.pType) {
        this.$refs.uToast.show({
          title: "请选择旅客类型",
          type: "error",
        });
        return;
      }
      // 手机号的校验
      let reg2 = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!reg2.test(this.form.phone)) {
        this.$refs.uToast.show({
          title: "手机号不符合规则",
          type: "error",
        });
        return;
      }
      // 证件的正则
      let flag = true;
      if (this.form.cardtype === "中国居民身份证") {
        flag = this.idCard(this.form.cardno);
      } else if (this.form.cardtype === "港澳台居民来往内地通行证") {
        flag = this.idCardGA(this.form.cardno);
      } else if (this.form.cardtype === "台湾居民来往大陆通行证") {
        flag = this.idCardTW(this.form.cardno);
      } else if (this.form.cardtype === "护照") {
        flag = this.idCardHZ(this.form.cardno);
      }
      if (!flag) {
        this.$refs.uToast.show({
          title: "请输入正确的证件号码",
          type: "error",
        });
        return;
      }
      // 获取身份证号然后转成年龄
      let diff = 0;
      if (this.form.cardtype === "中国居民身份证") {
        console.log(this.form.cardno.slice(6, 14));
        let ymd = this.form.cardno.slice(6, 14);
        diff = moment().diff(
          moment(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`),
          "year"
        );
      }
      console.log(diff);
      if (this.form.pType === "儿童") {
        // 如果是儿童 需加一层判断
        // 1、如果选的是身份证  需要判断身份证的年龄是不是正确
        if (this.form.cardtype === "中国居民身份证") {
          if (diff > 12) {
            this.$refs.uToast.show({
              title: "您已超过儿童票年龄上限，12周岁，请重新选择！",
              type: "error",
            });
            return;
          }
          if (diff < 6) {
            this.$refs.uToast.show({
              title: "儿童票的年龄下限是6周岁，你无须买票~",
              type: "error",
            });
            return;
          }
        } else {
          this.$refs.uToast.show({
            title: "请重新选择证件类型，非中国居民暂时无法使用儿童票~",
            type: "error",
          });
        }
      } else if (this.form.pType === "成人") {
        // 年龄小于12自动判断为儿童
        if (diff <= 12) {
          this.form.pType = "儿童";
        }
      }
      // 拷贝数据 防止修改污染页面展示
      let form = JSON.parse(JSON.stringify(this.form));
      // 处理存入数据库的参数
      form.cardtype =
        this.typeList.findIndex((v) => v.text === this.form.cardtype) + "";
      form.pType =
        this.typeList2.findIndex((v) => v.text === this.form.pType) + "";
        // 儿童无需认证
      form.examine = this.form.pType !== "儿童" ? "false" : "true";
      form.userid = this.userInfo.id;
      form.choose = "false";
      if (!this.$refs.uUpload && this.form.id) {
        // 处理图片
        form.pics = form.pics.map((v) => {
          return v.split("/")[3];
        });
        form.pics = JSON.stringify(form.pics);
      } else {
        form.pics =
          this.form.pType !== "成人" && this.form.pType !== "儿童"
            ? JSON.stringify(
                this.$refs.uUpload.lists.map((v) => v.response.imgName)
              )
            : "[]";
      }

      if (this.form.id) {
        // 编辑
        updatePass(this.form.id, form).then((res) => {
          if (res.code === 200) {
            if (this.form.self && this.form.self === 'true') {
              // 修改user表的pType
              updateUser(this.form.userid, {
                pType: form.pType
              }).then(res => {
                this.$refs.uToast.show({
                  title: "修改成功~",
                  type: "success",
                });
                uni.$emit("refreshData", {
                  refresh: true,
                });
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1,
                  });
                }, 500);
              })
            }
          } else {
            this.$refs.uToast.show({
              title: res.msg,
              type: "error",
            });
          }
        });
      } else {
        // 新增乘车人
        addPass(form).then((res) => {
          if (res.code === 200) {
            this.$refs.uToast.show({
              title: "添加成功~",
              type: "success",
            });
            uni.$emit("refreshData", {
              refresh: true,
            });
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 500);
          } else {
            this.$refs.uToast.show({
              title: res.msg,
              type: "error",
            });
          }
        });
      }
    },
    // 身份证的正则
    idCard(value) {
      return /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
        value
      );
    },
    // 港澳台居民来往内地通行证 的正则
    idCardGA(value) {
      return /^[H|M]\\d{10}|^[H|M]\\d{6}$/.test(value);
    },
    // 台湾居民来往大陆通行证的正则
    idCardGTW(value) {
      return /^\\d{8}|^[a-zA-Z0-9]{10}|^\\d{18}$/.test(value);
    },
    // 护照的正则
    idCardHZ(value) {
      return /^1[45][0-9]{7}|^[P|S]\\d{7}|^[S|G]\\d{8}$/.test(value);
    },
    reSubmit(examine) {
      if (examine === "true") {
        return;
      }
      this.fileList = [];
      this.form.pics = [];
      this.previewImg = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  min-height: 100vh;
  overflow: hidden;
  padding: 2rpx;
}
.block {
  padding: 20rpx;
  height: 120rpx;
  width: 100%;
  border: 1rpx solid lightgray;

  .avator {
    width: 100%;
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .position {
    width: 20rpx;
    height: 20rpx;
  }
}
.title {
  width: 100%;
  text-align: center;
  font-weight: bold;
  margin: 40rpx 0;
  font-size: 32rpx;
}

.each-row {
  width: 100%;
  padding: 0 20rpx;
  height: 100rpx;
  line-height: 100rpx;
  border-bottom: 1rpx solid #999;
}

.content {
  padding: 30rpx;
  width: 100%;
}

.submit {
  margin: 30rpx auto;
  border: none;
  width: calc(100% - 60rpx);
  height: 86rpx;
  line-height: 86rpx;
  box-sizing: border-box;
  border-radius: 15rpx;
  background-color: #5f88ff;
  color: #ffffff;
}
.imgs {
  padding: 30rpx;

  .img {
    width: 33%;
    height: 200rpx;
  }
  .submit2 {
    background: #ff5757;
    width: 40%;
  }
}
</style>
